package com.mozz.finally_work.servlet;

import com.mozz.finally_work.dao.UserDao;
import com.mozz.finally_work.pojo.User;
import com.mozz.finally_work.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import sun.misc.BASE64Encoder;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@WebServlet(name = "RegisterServlet", value = "/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String nickName = request.getParameter("nickName");
        String password = request.getParameter("password");
        String passwordAgain = request.getParameter("passwordAgain");
        String email = request.getParameter("email");
        // 验证合法性
        if (nickName == null || password == null || passwordAgain == null || email == null) {
            response.sendRedirect("register.jsp");
            return;
        }
        if (!password.equals(passwordAgain)) {
            response.sendRedirect("register.jsp");
            return;
        }
        // 密码md5加密
        MessageDigest md = null;
        String newPassword = null;
        try {
            md = MessageDigest.getInstance("MD5");
            BASE64Encoder encoder = new BASE64Encoder();
            newPassword = encoder.encode(md.digest(password.getBytes()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            response.sendRedirect("register.jsp");
        }
        // 使用UUID生成id
        UUID uuid = UUID.randomUUID();


        // 构建User对象
        User user = new User();
        user.setId(uuid.toString());
        user.setEmail(email);
        user.setPassword(newPassword);
        user.setNickName(nickName);
        // 调用dao添加记录
        SqlSession session = MybatisUtils.getSession();
        UserDao dao = session.getMapper(UserDao.class);
        Integer result = dao.addUser(user);
        System.out.println(user);
        System.out.println(result);
        session.commit();
        session.close();
        if (result!=0) {
            // 添加成功
            response.sendRedirect("login.jsp");
        }else{
            // 添加失败
            response.sendRedirect("register.jsp");
        }
    }
}
